<template>
  <div class="product-carousel">
    <el-carousel
      :interval="5000"
      :arrow="arrow"
      indicator-position="outside"
      :height="isMobile ? '240px' : '480px'"
      :autoplay="autoplay"
      :touch="true"
      class="carousel-root"
    >
      <el-carousel-item v-for="item in items" :key="item.id" class="carousel-item">
        <div class="slide" @click="goToDetail(item.id)">
          <div class="image-wrap">
            <img v-img-fallback :src="item.image" :alt="item.name" />
            <div class="info-wrap">
              <h3 class="name">{{ item.name }}</h3>
              <p class="desc">{{ item.description }}</p>
              <div class="price-row">
                <span class="price">¥{{ item.price }}</span>
                <span v-if="item.originalPrice" class="original">¥{{ item.originalPrice }}</span>
              </div>
              <div class="actions">
                <el-button type="danger" size="small" @click.stop="goToBuy(item)">去购买</el-button>
                <el-button type="warning" size="small" @click.stop="goToFavorites()">看收藏</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-carousel-item>
    </el-carousel>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { productApi } from '@/api/product'
import { resolveImage } from '@/utils/request'

const router = useRouter()
const isMobile = ref(false)
const arrow = computed(() => (isMobile.value ? 'never' : 'hover'))
const autoplay = computed(() => true)

const items = reactive([])

const checkScreenSize = () => {
  isMobile.value = window.innerWidth <= 768
}

const mapProduct = (p) => ({
  id: p.id,
  name: p.name,
  description: p.description || p.subtitle || '',
  image: resolveImage(p.image || p.mainImage || (p.images && p.images[0]) || ''),
  price: p.price,
  originalPrice: p.originalPrice || null
})

const fetchProducts = async () => {
  try {
    const params = { limit: 5 }
    let res = await productApi.getRecommendedProducts(params)
    let list = Array.isArray(res?.data) ? res.data : (res?.data?.list || [])
    if (!list || list.length === 0) {
      res = await productApi.getHotProducts(params)
      list = Array.isArray(res?.data) ? res.data : (res?.data?.list || [])
    }
    const mapped = list.slice(0, 5).map(mapProduct)
    items.splice(0, items.length, ...mapped)
  } catch (e) {
    ElMessage.error('加载轮播商品失败')
  }
}

const goToDetail = (id) => {
  router.push(`/product/${id}`)
}

const goToBuy = async (item) => {
  try {
    const detailRes = await productApi.getProductDetail(item.id)
    const p = detailRes?.data || {}
    const img = resolveImage((p.images && p.images[0]) || p.mainImage || item.image || '')
    const checkoutData = {
      items: [
        {
          cartId: null,
          productId: item.id,
          quantity: 1,
          specifications: {},
          price: Number(p.price ?? item.price ?? 0),
          product: { name: p.name || item.name, image: img }
        }
      ]
    }
    sessionStorage.setItem('checkoutData', JSON.stringify(checkoutData))
    router.push('/order/checkout')
  } catch (e) {
    router.push(`/product/${item.id}`)
  }
}

const goToFavorites = () => {
  router.push({ path: '/user', query: { tab: 'favorites' } })
}

onMounted(() => {
  checkScreenSize()
  window.addEventListener('resize', checkScreenSize)
  fetchProducts()
})

onUnmounted(() => {
  window.removeEventListener('resize', checkScreenSize)
})
</script>

<style scoped>
.product-carousel {
  width: 100%;
  height: 100%;
  display: block;
}

.carousel-root {
  width: 100%;
  height: 100%;
  display: block;
}

.carousel-root :deep(.el-carousel__container) {
  width: 100%;
  height: 100%;
}

.carousel-item {
  width: 100%;
  height: 100%;
}

.carousel-root :deep(.el-carousel__item) {
  width: 100%;
  height: 100%;
}

.slide {
  position: relative;
  width: 100%;
  height: 100%;
}

.image-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  background: #f7f7f7;
}

.image-wrap img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.info-wrap {
  position: absolute;
  left: 32px;
  bottom: 56px;
  right: auto;
  max-width: 36%;
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 16px;
  background: rgba(0, 0, 0, 0.45);
  border-radius: 8px;
  z-index: 2;
}

.name {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #fff;
}

.desc {
  margin: 0;
  color: #fff;
  opacity: 0.9;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.price-row {
  display: flex;
  gap: 12px;
  align-items: baseline;
}

.price {
  color: #ff6b6b;
  font-size: 24px;
  font-weight: 700;
}

.original {
  color: #eee;
  text-decoration: line-through;
}

.actions {
  display: flex;
  gap: 12px;
}

@media (max-width: 768px) {
  .carousel-root {
    min-height: 240px;
  }
  .image-wrap {
    height: 100%;
  }
  .info-wrap {
    left: 12px;
    right: 12px;
    bottom: 12px;
    max-width: none;
    padding: 12px;
  }
  .name {
    font-size: 18px;
  }
  .price {
    font-size: 20px;
  }
}
</style>